package yiran.stock.manager;

import yiran.stock.StockManager;
import yiran.stock.output.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class StockDataFetcher {
    private final StockManager stockManager;
    
    public StockDataFetcher(StockManager stockManager) {
        this.stockManager = stockManager;
    }

    public String fetchApiData(String symbol) throws IOException {
        int retryCount = 0;
        while (true) {
            try {
                String apiUrl = stockManager.getCurrentApiProvider().baseUrl + symbol.toLowerCase();
                HttpURLConnection conn = createConnection(apiUrl);

                int responseCode = conn.getResponseCode();
                if (responseCode != 200) {
                    throw new IOException("API请求失败，HTTP状态码: " + responseCode);
                }

                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), "GBK"))) {

                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    return response.toString();
                }
            } catch (IOException e) {
                retryCount++;
                if (retryCount < StockManager.MAX_RETRIES) {
                    Logger.warn("股票 " + symbol + " 请求失败，重试中 (" + retryCount + "/" + StockManager.MAX_RETRIES + ")");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                    }
                } else {
                    throw e;
                }
            }
        }
    }

    private HttpURLConnection createConnection(String apiUrl) throws IOException {
        URL url = new URL(apiUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(3000);
        conn.setReadTimeout(5000);
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        conn.setRequestProperty("Referer", "https://gu.qq.com/");

        return conn;
    }

    public String[] parseApiResponse(String response) throws IOException {
        if (response == null || response.isEmpty()) {
            throw new IOException("API响应为空");
        }

        int startIndex = response.indexOf('"');
        if (startIndex == -1) throw new IOException("无效的API响应格式：缺少引号");

        int endIndex = response.indexOf('"', startIndex + 1);
        if (endIndex == -1) throw new IOException("无法定位数据部分结尾");

        String dataContent = response.substring(startIndex + 1, endIndex);

        if (dataContent.isEmpty()) {
            throw new IOException("数据内容为空");
        }

        return dataContent.split("~", -1);
    }
}
